package xnj.lazydog.btcontroller.MyViews;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

import xnj.lazydog.btcontroller.ControlViews.ControlView;

public class SideToolBar extends View {

    private static final String TAG = "SideToolBar";
    final float BUTTON_SIZE = 4.3f;
    final float BUTTON_SPACE = 9;
    final float PRESSED_SCALE= 1.2f;
    final int BACK_COLOR = 0x88bbbbc3;
    final int CIRCLE_COLOR = 0x88000000;
    final float CIRCLE_RATIO = 0.8f;

    float center_px=0,center_py=0;
    float bmp_size=0,bmp_space=0;

    public float mm2pix_k;
    public float w=0,h=0;

    Bitmap quit;
    Bitmap [] tools;
    Bitmap [] buttons;

    float quit_scale;
    float [] tools_scale;
    float [] buttons_scale;


    int quit_id=0;
    List<Integer> tools_id = new ArrayList<>();
    List<Integer> buttons_id = new ArrayList<>();

    public int toolMode=0;


    Paint p;
    public SideToolBar(Context context,AttributeSet attrs) {
        super(context, attrs);
        initPIXMM();
        p = new Paint();

        p.setFlags(Paint.FILTER_BITMAP_FLAG);
        p.setAntiAlias(true);
    }

    public void configure(int id,SideToolBarListener listener)
    {
        quit_id = id;
        this.listener = listener;
    }

    public void addTool(int id)
    {
        tools_id.add(id);
    }
    public void addButton(int id)
    {
        buttons_id.add(id);
    }


    float sum;
    RectF rectF = new RectF();
    float rect_margin = 0.0666f;
    float tool_select_y;
    float tool_select_y_set;


    @Override
    protected void onDraw(Canvas canvas) {


        if(center_px==0)
            init();

        sum =0;
        //Log.w(TAG, "onDraw:");

        // draw quit button
        p.setColor(BACK_COLOR);

        //canvas.drawRect(center_px-bmp_size*0.5f,center_py-bmp_size*0.5f,center_px+bmp_size*0.5f,center_py+bmp_size*0.5f,p);
        sum  = quit_scale-1;
        if(quit!=null) {
            canvas.drawCircle(center_px,center_py,bmp_space*0.4333f,p);
            p.setAlpha(255);
            draw(canvas, center_px, center_py, quit_scale, quit);
        }
        //draw tools

        if(tools.length>0)
        {

            tool_select_y_set =center_py+(toolMode+1)*bmp_space;
            tool_select_y+=(tool_select_y_set-tool_select_y)*0.15f;
            sum+=Math.abs(tool_select_y_set-tool_select_y);

            rectF.left = w-bmp_space*(1-rect_margin);
            rectF.right =w-bmp_space*rect_margin;
            rectF.top = bmp_space*(1+rect_margin);
            rectF.bottom = bmp_space*(tools.length+1-rect_margin);

            p.setColor(BACK_COLOR);
            canvas.drawRoundRect(rectF,bmp_space*(0.5f-rect_margin),bmp_space*(0.5f-rect_margin),p);

            p.setColor(CIRCLE_COLOR);
            canvas.drawCircle(center_px,tool_select_y,bmp_space*0.5f*CIRCLE_RATIO,p);

            p.setAlpha(255);

            for(int i=0;i<tools_id.size();i++)
            {
             if(tools[i]!=null)
             {
                 draw(canvas,center_px,center_py+(i+1)*bmp_space,tools_scale[i],tools[i]);
                 sum+=tools_scale[i]-1;
             }
            }
        }

        //draw buttons
        if(buttons.length>0)
        {
            for(int i=0;i<buttons_id.size();i++)
            {
                if(buttons[i]!=null)
                {
                    p.setColor(BACK_COLOR);
                    canvas.drawCircle(center_px-(i+1)*bmp_space,center_py,bmp_space*(0.5f-rect_margin),p);
                    p.setAlpha(255);
                    draw(canvas,center_px-(i+1)*bmp_space,center_py,buttons_scale[i],buttons[i]);
                    sum+=buttons_scale[i]-1;
                }
            }
        }

        if(sum>0.005f) {
            quit_scale -= (quit_scale-1)*0.1f;

            for(int i=0;i<tools_scale.length;i++)
                tools_scale[i] += (1-tools_scale[i])*0.1f;
            for(int i=0;i<buttons_scale.length;i++)
                buttons_scale[i] += (1-buttons_scale[i])*0.1f;

            invalidate();
        }else
        {
            quit_scale = 1;
            for(int i=0;i<tools_scale.length;i++)
                tools_scale[i] = 1;
            for(int i=0;i<buttons_scale.length;i++)
                buttons_scale[i] = 1;
        }
    }

    float bmp_w,bmp_h;
    void draw(Canvas canvas,float x,float y,float scale,Bitmap bitmap)
    {
        canvas.save();
        canvas.translate(x,y);
        canvas.scale(scale,scale);
        //canvas.drawRect(-bmp_size*0.5f,-bmp_size*0.5f,bmp_size*0.5f,bmp_size*0.5f,p);
        bmp_w = bitmap.getWidth();
        bmp_h = bitmap.getHeight();
        canvas.drawBitmap(bitmap,-bmp_w*0.5f,-bmp_h*0.5f,p);
        canvas.restore();
    }


    void init()
    {
        w = getWidth();
        h = getHeight();
        bmp_size = mm2Pix(BUTTON_SIZE);
        bmp_space = mm2Pix(BUTTON_SPACE);
        center_px = w-bmp_space*0.5f;
        center_py = bmp_space*0.5f;
        tool_select_y = center_py+bmp_space;
        //Log.w(TAG, "init: bmp:"+bmp_size+" bmps:"+bmp_space+" cx:"+center_px+"  cy:"+center_py);
        //if(quit_id!=0)
        {
            quit=IDBitmap.getBitmapScaled(getResources(),quit_id,bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
            quit_scale = 1;
        }
        //if(tools_id.size()>0)
        {
            tools = new Bitmap[tools_id.size()];
            tools_scale = new float[tools_id.size()];

            for(int i=0;i<tools.length;i++)
            {
                tools[i] = IDBitmap.getBitmapScaled(getResources(),tools_id.get(i),bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
                tools_scale[i] = 1;
            }
        }
        //if(buttons_id.size()>0)
        {
            buttons = new Bitmap[buttons_id.size()];
            buttons_scale = new float[buttons_id.size()];
            for(int i=0;i<buttons.length;i++)
            {
                buttons[i] = IDBitmap.getBitmapScaled(getResources(),buttons_id.get(i),bmp_size,bmp_size,IDBitmap.BMP_MODE_WRAP);
                buttons_scale[i] = 1;
            }
        }
    }

    void initPIXMM()
    {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);

        if(windowManager!=null) {
            Display display = windowManager.getDefaultDisplay();
            DisplayMetrics metrics = new DisplayMetrics();
            display.getMetrics(metrics);

            //mm2pix_k = (metrics.xdpi + metrics.ydpi) / 50.8f;

            mm2pix_k = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1,metrics);

            //Log.w(TAG, "initPIXMM: "+mm2pix_k );

            w = metrics.widthPixels;
            h = metrics.heightPixels;
        }else
            mm2pix_k = 16;
    }


    int mm2Pix(float mm)
    {
        return (int)(mm*mm2pix_k);
    }

    float pix2MM(float pix)
    {
        return pix/mm2pix_k;
    }



    boolean isDragging = false;
    float px,py;
    float fx,fy;
    int index;
    public ControlView controlView;
    boolean hitDog;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        px = event.getX();
        py = event.getY();

        hitDog = false;
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            if(px>w-bmp_space&&py<bmp_space)
            {
                quit_scale = PRESSED_SCALE;
                postInvalidate();
                hitDog = true;
            }else
            {
                if(px<w-bmp_space)
                {
                    if(py<bmp_space)   // button
                    {
                        index = (int)((w-bmp_space-px)/bmp_space);
                        if(index>=0&&index<buttons_id.size()) {
                            buttons_scale[index] = PRESSED_SCALE;
                            hitDog = true;
                            postInvalidate();
                        }
                    }
                }else if(py<(tools_id.size()+1)*bmp_space) // tool
                {
                    index = (int)((py-bmp_space)/bmp_space);
                    if(index>=0&&index<tools_id.size()) {
                      tools_scale[index] = PRESSED_SCALE;
                      postInvalidate();
                      hitDog = true;
                    }
                }
            }
            fx = px;
            fy = py;
        }

        if(event.getAction()==MotionEvent.ACTION_MOVE)
        {
            if((px-fx)*(px-fx)+(py-fy)*(py-fy)>600)
            {
                isDragging = true;
            }
        }
        if(event.getAction()==MotionEvent.ACTION_UP)
        {

            if(!isDragging)
            {

                if(listener!=null)
                {

                    if(px>w-bmp_space&&py<bmp_space)
                    {
                        listener.onQuitEvent();
                        hitDog = true;
                    }else
                    {
                        if(px<w-bmp_space)
                        {
                            if(py<bmp_space)   // button
                            {
                                index = (int)((w-bmp_space-px)/bmp_space);
                                if(index>=0&&index<buttons_id.size()) {
                                    hitDog = true;
                                    listener.onButtonEvent(index);
                                }
                            }
                        }else if(py<(tools_id.size()+1)*bmp_space) // tool
                        {
                            index = (int)((py-bmp_space)/bmp_space);
                            if(index>=0&&index<tools_id.size()) {
                                listener.onToolEvent(index);
                                toolMode = index;
                                hitDog = true;
                            }

                        }
                    }
                }
            }
            isDragging = false;
        }
        if(controlView!=null)
            controlView.onTouched(event,hitDog);

        return true;
    }

    public interface SideToolBarListener{
        void onToolEvent(int toolIndex);
        void onButtonEvent(int buttonIndex);
        void onQuitEvent();
    }
    SideToolBarListener listener;


}
